package com.example.administrator.wallet.view.activity.find.cointrans;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.administrator.wallet.R;
import com.example.administrator.wallet.base.BaseActivity;
import com.example.administrator.wallet.constant.Constant;
import com.example.administrator.wallet.custom.MessageEvent;
import com.example.administrator.wallet.custom.MyWebSocketClient;
import com.example.administrator.wallet.custom.MyWebSocketService;
import com.example.administrator.wallet.model.bean.WebSocketDepthBean;
import com.example.administrator.wallet.model.bean.WebSocketPriceBean;
import com.example.administrator.wallet.model.bean.WebSocketTodayMarketBean;
import com.example.administrator.wallet.utils.SharedPrefsUtil;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

public class CoinTransactionDetailsKLineActivity extends BaseActivity {

    @Bind(R.id.tv_price_buy_1_activity_kline)
    TextView tvPriceBuy1;
    @Bind(R.id.tv_price_buy_2_activity_kline)
    TextView tvPriceBuy2;
    @Bind(R.id.tv_price_buy_3_activity_kline)
    TextView tvPriceBuy3;
    @Bind(R.id.tv_price_buy_4_activity_kline)
    TextView tvPriceBuy4;
    @Bind(R.id.tv_price_buy_5_activity_kline)
    TextView tvPriceBuy5;
    @Bind(R.id.tv_price_buy_6_activity_kline)
    TextView tvPriceBuy6;
    @Bind(R.id.tv_price_buy_7_activity_kline)
    TextView tvPriceBuy7;
    @Bind(R.id.tv_price_buy_8_activity_kline)
    TextView tvPriceBuy8;
    @Bind(R.id.tv_price_buy_9_activity_kline)
    TextView tvPriceBuy9;
    @Bind(R.id.tv_price_buy_10_activity_kline)
    TextView tvPriceBuy10;

    @Bind(R.id.tv_price_sell_1_activity_kline)
    TextView tvPriceSell1;
    @Bind(R.id.tv_price_sell_2_activity_kline)
    TextView tvPriceSell2;
    @Bind(R.id.tv_price_sell_3_activity_kline)
    TextView tvPriceSell3;
    @Bind(R.id.tv_price_sell_4_activity_kline)
    TextView tvPriceSell4;
    @Bind(R.id.tv_price_sell_5_activity_kline)
    TextView tvPriceSell5;
    @Bind(R.id.tv_price_sell_6_activity_kline)
    TextView tvPriceSell6;
    @Bind(R.id.tv_price_sell_7_activity_kline)
    TextView tvPriceSell7;
    @Bind(R.id.tv_price_sell_8_activity_kline)
    TextView tvPriceSell8;
    @Bind(R.id.tv_price_sell_9_activity_kline)
    TextView tvPriceSell9;
    @Bind(R.id.tv_price_sell_10_activity_kline)
    TextView tvPriceSell10;

    @Bind(R.id.tv_quantity_buy_1_activity_kline)
    TextView tvQuantityBuy1;
    @Bind(R.id.tv_quantity_buy_2_activity_kline)
    TextView tvQuantityBuy2;
    @Bind(R.id.tv_quantity_buy_3_activity_kline)
    TextView tvQuantityBuy3;
    @Bind(R.id.tv_quantity_buy_4_activity_kline)
    TextView tvQuantityBuy4;
    @Bind(R.id.tv_quantity_buy_5_activity_kline)
    TextView tvQuantityBuy5;
    @Bind(R.id.tv_quantity_buy_6_activity_kline)
    TextView tvQuantityBuy6;
    @Bind(R.id.tv_quantity_buy_7_activity_kline)
    TextView tvQuantityBuy7;
    @Bind(R.id.tv_quantity_buy_8_activity_kline)
    TextView tvQuantityBuy8;
    @Bind(R.id.tv_quantity_buy_9_activity_kline)
    TextView tvQuantityBuy9;
    @Bind(R.id.tv_quantity_buy_10_activity_kline)
    TextView tvQuantityBuy10;

    @Bind(R.id.tv_quantity_sell_1_activity_kline)
    TextView tvQuantitySell1;
    @Bind(R.id.tv_quantity_sell_2_activity_kline)
    TextView tvQuantitySell2;
    @Bind(R.id.tv_quantity_sell_3_activity_kline)
    TextView tvQuantitySell3;
    @Bind(R.id.tv_quantity_sell_4_activity_kline)
    TextView tvQuantitySell4;
    @Bind(R.id.tv_quantity_sell_5_activity_kline)
    TextView tvQuantitySell5;
    @Bind(R.id.tv_quantity_sell_6_activity_kline)
    TextView tvQuantitySell6;
    @Bind(R.id.tv_quantity_sell_7_activity_kline)
    TextView tvQuantitySell7;
    @Bind(R.id.tv_quantity_sell_8_activity_kline)
    TextView tvQuantitySell8;
    @Bind(R.id.tv_quantity_sell_9_activity_kline)
    TextView tvQuantitySell9;
    @Bind(R.id.tv_quantity_sell_10_activity_kline)
    TextView tvQuantitySell10;

    @Bind(R.id.finish_img)
    ImageButton ibBack;
    @Bind(R.id.view_title)
    TextView tvTitle;
    @Bind(R.id.iv_more_record_toolbar)
    ImageView ivMoreRecord;
    @Bind(R.id.iv_k_line_toolbar)
    ImageView ivKLine;
    @Bind(R.id.iv_add_to_self_toolbar)
    ImageView ivAddToSelf;

    @Bind(R.id.tv_price_kline_activity)
    TextView tvPrice;
    @Bind(R.id.tv_chinese_price_kline_activity)
    TextView tvChinesePrice;
    @Bind(R.id.tv_up_or_down_percent_kline_activity)
    TextView tvUpOrDownPercent;
    @Bind(R.id.tv_24h_highest_price_kline_activity)
    TextView tv24hHighestPrice;
    @Bind(R.id.tv_24h_lowest_price_kline_activity)
    TextView tv24hLowestPrice;

    MyWebSocketClient client;
    private String token;
    private WebSocketPriceBean priceBean;
    private WebSocketTodayMarketBean todayMarketBean;
    private int joinId;
    private String market;
    private int priceId;
    private int todayId;
    private int depthId;
    private String strUPOrDownPercent;
    private Gson mGson;
    private WebSocketDepthBean webSocketDepthBean;

    private List<TextView> priceBuyList;
    private List<TextView> priceSellList;
    private List<TextView> quantityBuyList;
    private List<TextView> quantitySellList;

    private List<String> priceBuyData;
    private List<String> priceSellData;
    private List<String> quantityBuyData;
    private List<String> quantitySellData;

    private MyWebSocketService myWebSocketService;
    private ServiceConnection serviceConnection;

    @Override
    public void init() {
        EventBus.getDefault().register(this);
        initViewTextViews();
        initView();
        initData();
    }

    private void initView() {
        ivMoreRecord.setVisibility(View.GONE);
        ivKLine.setVisibility(View.GONE);
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ivAddToSelf.getLayoutParams();
        params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        ivAddToSelf.setLayoutParams(params);

        Intent intent = getIntent();
        String title = intent.getStringExtra(Constant.TO_KLINE_ACTIVITY_TITLE);
        tvTitle.setText(title);

        String[] markets = title.split("/");
        market = markets[0] + markets[1];
    }

    private void initData() {

        mGson = new Gson();
        token = SharedPrefsUtil.getValue(this, "wallet", "token", "");

        serviceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                myWebSocketService = ((MyWebSocketService.ServiceBinder) service).getService();

                JSONArray jsonArray = new JSONArray();
                jsonArray.add(market);
                priceId = myWebSocketService.sendMessage("price.query",jsonArray);
                todayId = myWebSocketService.sendMessage("today.query",jsonArray);

                jsonArray.add(10);
                jsonArray.add("0");
                depthId = myWebSocketService.sendMessage("depth.query",jsonArray);
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };

        bindService(new Intent(this,MyWebSocketService.class),serviceConnection, Context.BIND_AUTO_CREATE);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(MessageEvent event){
        JSONObject jsonObject = (JSONObject) JSONObject.parse(event.getMessage());
        if (jsonObject.getInteger("id") == priceId){
            tvPrice.setText(jsonObject.getString("result"));
        } else if (jsonObject.getInteger("id") == todayId){
            if (jsonObject.get("result") != null){
                final JSONObject json = jsonObject.getJSONObject("result");

                Double openNumber = Double.parseDouble(json.getString("open"));
                Double lastNumber = Double.parseDouble(json.getString("last"));

                final double upsOrDown = (lastNumber-openNumber)/openNumber;

                final String strUPOrDown = String.format("%.2f", upsOrDown);

                if (upsOrDown < 0){
                    strUPOrDownPercent = strUPOrDown;
                } else {
                    strUPOrDownPercent = "+" + strUPOrDown;
                }

                tvUpOrDownPercent.setText(strUPOrDownPercent);
                tv24hHighestPrice.setText(json.getString("high"));
                tv24hLowestPrice.setText(json.getString("low"));

            }
        } else if (jsonObject.getInteger("id") == depthId){
            webSocketDepthBean = mGson.fromJson(event.getMessage(),WebSocketDepthBean.class);
            List<List<String>> asks = webSocketDepthBean.getResult().getAsks();
            List<List<String>> bids = webSocketDepthBean.getResult().getBids();

            depthDataClear();

            for (List<String> ask : asks) {
                priceSellData.add(ask.get(0));
                quantitySellData.add(ask.get(1));
            }
            for (List<String> bid : bids) {
                priceBuyData.add(bid.get(0));
                quantityBuyData.add(bid.get(1));
            }

            setDepthListData();
        }
    }

    @Override
    public int getLayoutResource() {
        return R.layout.activity_coin_transaction_details_kline;
    }

    @OnClick(R.id.finish_img)
    public void onViewClicked() {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if(EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    private void setDepthListData() {
        for (int i = 0; i < priceBuyData.size(); i++) {
            priceBuyList.get(i).setText(priceBuyData.get(i));
            quantityBuyList.get(i).setText(quantityBuyData.get(i));
        }
        for (int i = 0; i < priceSellData.size(); i++) {
            priceSellList.get(i).setText(priceSellData.get(i));
            quantitySellList.get(i).setText(quantitySellData.get(i));
        }
    }

    private void depthDataClear() {
        priceBuyData.clear();
        priceSellData.clear();
        quantityBuyData.clear();
        quantitySellData.clear();

        for (int i = 0; i < 10; i++) {
            priceBuyList.get(i).setText("");
            priceSellList.get(i).setText("");
            quantityBuyList.get(i).setText("");
            quantitySellList.get(i).setText("");
        }
    }

    private void initViewTextViews() {
        priceBuyList = new ArrayList<>();
        priceSellList = new ArrayList<>();
        quantityBuyList = new ArrayList<>();
        quantitySellList = new ArrayList<>();

        priceBuyData = new ArrayList<>();
        priceSellData = new ArrayList<>();
        quantityBuyData = new ArrayList<>();
        quantitySellData = new ArrayList<>();

        priceBuyList.add(tvPriceBuy1);
        priceBuyList.add(tvPriceBuy2);
        priceBuyList.add(tvPriceBuy3);
        priceBuyList.add(tvPriceBuy4);
        priceBuyList.add(tvPriceBuy5);
        priceBuyList.add(tvPriceBuy6);
        priceBuyList.add(tvPriceBuy7);
        priceBuyList.add(tvPriceBuy8);
        priceBuyList.add(tvPriceBuy9);
        priceBuyList.add(tvPriceBuy10);

        priceSellList.add(tvPriceSell1);
        priceSellList.add(tvPriceSell2);
        priceSellList.add(tvPriceSell3);
        priceSellList.add(tvPriceSell4);
        priceSellList.add(tvPriceSell5);
        priceSellList.add(tvPriceSell6);
        priceSellList.add(tvPriceSell7);
        priceSellList.add(tvPriceSell8);
        priceSellList.add(tvPriceSell9);
        priceSellList.add(tvPriceSell10);

        quantityBuyList.add(tvQuantityBuy1);
        quantityBuyList.add(tvQuantityBuy2);
        quantityBuyList.add(tvQuantityBuy3);
        quantityBuyList.add(tvQuantityBuy4);
        quantityBuyList.add(tvQuantityBuy5);
        quantityBuyList.add(tvQuantityBuy6);
        quantityBuyList.add(tvQuantityBuy7);
        quantityBuyList.add(tvQuantityBuy8);
        quantityBuyList.add(tvQuantityBuy9);
        quantityBuyList.add(tvQuantityBuy10);

        quantitySellList.add(tvQuantitySell1);
        quantitySellList.add(tvQuantitySell2);
        quantitySellList.add(tvQuantitySell3);
        quantitySellList.add(tvQuantitySell4);
        quantitySellList.add(tvQuantitySell5);
        quantitySellList.add(tvQuantitySell6);
        quantitySellList.add(tvQuantitySell7);
        quantitySellList.add(tvQuantitySell8);
        quantitySellList.add(tvQuantitySell9);
        quantitySellList.add(tvQuantitySell10);
    }
}
